package com.android.server.mock.performer.settings;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MockSettingsItemHolder {
    private static final String TAG = "MockSettingsItemHolder";

    List<MockSettingsItem> globalList = new ArrayList<>();
    List<MockSettingsItem> secureList = new ArrayList<>();
    List<MockSettingsItem> systemList = new ArrayList<>();
    
    public static MockSettingsItemHolder create(String jsonStr) {
        MockSettingsItemHolder holder = new MockSettingsItemHolder();
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            holder.globalList.addAll(parseItem(jsonObject, "globalList"));
            holder.secureList.addAll(parseItem(jsonObject, "secureList"));
            holder.systemList.addAll(parseItem(jsonObject, "systemList"));
        } catch (JSONException e) {
            Log.e(TAG, "create, parseJsonError:", e);
        }
        return holder;
    }

    private static List<MockSettingsItem> parseItem(JSONObject json, String key) {
        JSONArray list = json.optJSONArray(key);
        if (list == null || list.length() == 0) {
            return new ArrayList<>();
        }

        List<MockSettingsItem> itemList = new ArrayList<>();
        for (int i = 0; i < list.length() - 1; i++) {
            try {
                MockSettingsItem item = MockSettingsItem.create(list.getJSONObject(i));
                if (item == null) {
                    continue;
                }
                itemList.add(item);
            } catch (JSONException e) {
                Log.e(TAG, "parseItem, parseJsonError:" + i, e);
            }
        }
        return itemList;
    }


    public List<MockSettingsItem> getGlobalList() {
        return globalList;
    }

    public List<MockSettingsItem> getSecureList() {
        return secureList;
    }

    public List<MockSettingsItem> getSystemList() {
        return systemList;
    }
}
